package com.okcl.security;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.okcl.utils.RedisClient;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Objects;

/**
 * 登录认证过滤器
 */
@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Resource
    private RedisClient redisClient;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取请求头里的token
        String token = request.getHeader("token");
        if (StringUtils.hasText(token)) {
            String key = "login:token:" + token;
            String json = redisClient.get(key);
            if (StringUtils.hasText(json)) {
                try {
                    //解析JSON对象
                    JSONObject jsonObject = JSONUtil.parseObj(json);
//                    //提取user字段并反序列化为User对象
//                    User user = jsonObject.get("user", User.class);
                    LoginUserDetails userDetails = JSONUtil.toBean(jsonObject, LoginUserDetails.class);
                    if (Objects.nonNull(userDetails)) {
                        //创建LoginUserDetails对象
                        // LoginUserDetails userDetails = new LoginUserDetails(user.getUser());
                        //封装用户信息
                        Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                        SecurityContextHolder.getContext().setAuthentication(authentication);
                    } else {
                        SecurityContextHolder.getContext().setAuthentication(null);
                    }
                } catch (Exception e) {
                    log.error("反序列化用户信息失败", e);
                    SecurityContextHolder.getContext().setAuthentication(null);
                }
            }
        }
        //放行
        filterChain.doFilter(request, response);
    }

}
